﻿/*
 * 选择测试目录及项。 2009-4-13 * 
 * 
 *2009-11-18: 此文件已作废。SZJ
 **/

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using EQT.Model;
using EQT.Dal;
using System.Collections.Generic;

public partial class SelectTestItem : System.Web.UI.Page
{

    DaContract dac = new DaContract(DaCommon.DefaultDb);//合同
    DaTestCatalog datc = new DaTestCatalog(DaCommon.DefaultDb);//测试目录
    DaTestItem dati = new DaTestItem(DaCommon.DefaultDb);//测试项
    DaCoTestItem dacti = new DaCoTestItem(DaCommon.DefaultDb);//合同执行测试项


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string report_id = Request.QueryString["report_id"];
            if (String.IsNullOrEmpty(report_id))
            {
                Utility.SiteError("缺失所必需的参数【合同编号】", Response);
            }
            else
            {
                ViewState["REPORT_ID"] = report_id;
            }
            MoContract moc = dac.GetEntity(report_id);
            if (moc != null)
            {
                TextBoxTotalPrice.Text = moc.Total_Price.ToString("F2");//合同报价
                TextBoxCharge.Text = moc.Charge.ToString("F2");//合同实际价格
                if (moc.Total_Price > 0)
                {
                    TextBoxDiscountRate.Text = (moc.Charge*100 / moc.Total_Price).ToString();
                }
                else
                {
                    TextBoxDiscountRate.Text = "100";
                }

            }
            else
            {
                Utility.SiteError("【合同编号】" + report_id + "无效.", Response);
            }

            BindTestCatalog(); //绑定测试项目录
            BindTestItems();
            BindSelectedTestItems();

           
        }
    }

    /// <summary>
    /// 选中1个检验项
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewTestItemSelected_Click(object sender, EventArgs e)
    {
        UserContext uc = Session["USER_CONTEXT"] as UserContext;
        if (uc == null)
        {
            Utility.SiteError("会话过期", Response);
            return;
        }

        LinkButton btn = sender as LinkButton;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string item_code = (string)GridViewTestItem.DataKeys[gvr.RowIndex].Value;//检验项       
        MoCoTestItem mocti= dacti.CreateCoTestItem(ViewState["REPORT_ID"].ToString(), item_code);
        try
        {
            dacti.Add(mocti); //添加新的检验项
        }
        catch (Exception ex)
        {
            Utility.GlobalLog.Error("添加检验项失败!", ex);
            return;
        }
         
      
        BindTestItems();
        BindSelectedTestItems();

        //按现行的折扣更新总价和价格
        //在这里做一次更新数据库的操作

        decimal charge = 0;
        decimal totalPrice = 0;
        if (decimal.TryParse(TextBoxCharge.Text, out charge) && decimal.TryParse(TextBoxTotalPrice.Text, out totalPrice))
        {
            dac.UpdateCharge(uc.UserID, totalPrice, charge, ViewState["REPORT_ID"].ToString());
        }
        else
        {
            Utility.SiteError("价格不可识别！");
        }
    }

    /// <summary>
    /// 移除一个选中的项
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewTestItemRemoveSelected_Click(object sender, EventArgs e)
    {
        UserContext uc = Session["USER_CONTEXT"] as UserContext;
        if (uc == null)
        {
            Utility.SiteError("会话过期", Response);
            return;
        }
        LinkButton btn = sender as LinkButton;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string co_item_id = (string)GridViewSelected.DataKeys[gvr.RowIndex].Value;//合同检验项
        //TODO:从合同中移除选定的检验项
        dacti.Delete(co_item_id);
        BindTestItems();
        BindSelectedTestItems();
        
        //按现行的折扣更新总价和价格
        //在这里做一次更新数据库的操作

        decimal charge=0;
        decimal totalPrice=0;
        if (decimal.TryParse(TextBoxCharge.Text, out charge) && decimal.TryParse(TextBoxTotalPrice.Text, out totalPrice))
        {
            dac.UpdateCharge(uc.UserID, totalPrice, charge, ViewState["REPORT_ID"].ToString());
        }
        else
        {
            Utility.SiteError("价格不可识别！");
        }
         

        
    }

    /// <summary>
    /// 绑定目录树
    /// </summary>
    private void BindTestCatalog()
    {
        tvTestCatalog.Nodes.Clear();
        Dictionary<string, TreeNode> tnDic = new Dictionary<string, TreeNode>();
        DataSet ds= datc.GetAllDescTestCatalogTreeDs();
        if (ds != null && ds.Tables.Count>0)
        {
            DataTable dt = ds.Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                TreeNode tn = new TreeNode(dr["TEST_CTG_NAME"].ToString(), dr["Test_Ctg_ID"].ToString());
                //具有父ID
                if (dr["PARENT_CTG_ID"] != null && dr["PARENT_CTG_ID"] != DBNull.Value)
                {
                    string p = dr["PARENT_CTG_ID"].ToString();
                    TreeNode tnp= tnDic[p];
                    tnp.ChildNodes.Add(tn);
                }
                else //没有父ID，就直接添加到字典中
                {
                    if (tnDic.ContainsKey(tn.Value) == false)
                    {
                        tnDic.Add(tn.Value, tn);
                        tvTestCatalog.Nodes.Add(tn);
                    }
                    else
                    {
                        throw new EqtException("在目录中，发现重复的根目录");
                    }
                }
                 
            }
        }
        tvTestCatalog.ExpandAll();
        tvTestCatalog.ExpandDepth = 3;        
      
    }   


    /// <summary>
    /// 绑定测试项列表
    /// </summary>
    private void BindTestItems()
    {
        if (!String.IsNullOrEmpty(tvTestCatalog.SelectedValue))
        {
            string dir_id = tvTestCatalog.SelectedValue;
            string report_id = ViewState["REPORT_ID"].ToString();
            GridViewTestItem.DataSource = dati.GetTestItem2Select(dir_id, report_id);
            GridViewTestItem.DataBind();            
        }
    }

    /// <summary>
    /// 绑定选中的测试项列表，这里会更新TextBoxTotalPrice
    /// </summary>
    private void BindSelectedTestItems()
    {

        DataSet ds= dacti.Query(String.Format( " WHERE Report_ID='{0}' AND Test_Status>0", ViewState["REPORT_ID"].ToString()));
        if (ds != null && ds.Tables.Count > 0)
        {
            GridViewSelected.DataSource = ds;
            GridViewSelected.DataBind();
            if (ds.Tables[0].Rows.Count > 0)
            {
                decimal totalPrice=Convert.ToDecimal(ds.Tables[0].Compute("SUM(Price)", ""));
                TextBoxTotalPrice.Text =String.Format("{0,9:F2}", totalPrice);//自动价格
                MoContract moc = dac.GetEntity(ViewState["REPORT_ID"].ToString());//数据库中存储的合同基本数据
                if (moc != null)
                {
                    int discountRate = 100;
                    if (!Int32.TryParse(TextBoxDiscountRate.Text, out discountRate)) //从UI得出当前的discount
                    {
                        discountRate = 100;
                        TextBoxDiscountRate.Text = "100";
                    }
                    decimal charge = totalPrice * discountRate / 100;
                    TextBoxCharge.Text = charge.ToString();//合同实际价格          

                }
                else
                {
                    Utility.SiteError("合同编号无效！", Response);
                    return;
                }
            }
            else //如果没有选择任何项
            {
                TextBoxTotalPrice.Text = "0";
                TextBoxDiscountRate.Text = "100";
            }
        }        


    }

   

    /// <summary>
    /// 选择的目录发生了改变
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        BindTestItems();//绑定测试项
    }
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        //清理Session变量
        string url = String.Format("CreateContract.aspx?reportid={0}", ViewState["REPORT_ID"]);
        Response.Redirect(url);
    }

    /// <summary>
    /// 设置最终价格
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnSetCharge_Click(object sender, EventArgs e)
    {
        decimal charge = 0;
        if (Decimal.TryParse(TextBoxCharge.Text, out charge) == true)
        {
            UserContext uc = Session["USER_CONTEXT"] as UserContext;
            if (uc == null)
            {
                Utility.SiteError("会话过期", Response);
                return;
            }
            else
            {
                decimal total_parice = 0;
                Decimal.TryParse(TextBoxTotalPrice.Text, out total_parice);
                if (total_parice >= charge)
                {
                    TextBoxDiscountRate.Text = String.Format("{0}", Convert.ToInt32(100 * charge / total_parice));
                }
                else
                {
                    TextBoxDiscountRate.Text = "100";
                    Utility.SiteError("总价格不应小于实际金额");
                    return;
                }
                dac.UpdateCharge(uc.UserID, total_parice, charge, ViewState["REPORT_ID"].ToString());
                labelInfo.Text = String.Format("更新合同总价成功!");


            }
        }
        else
        {
            labelInfo.Text = String.Format("错误：合同总价字符串不可识别！");
        }
    }

    /// <summary>
    /// 设定折扣率
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnSetDiscountRate_Click(object sender, EventArgs e)
    {
        int discount = 100;//折扣率
        if (Int32.TryParse(TextBoxDiscountRate.Text, out discount) == true)
        {
            if (discount > 100)
            {
                discount = 100;
            }
            MoContract moc = dac.GetEntity(ViewState["REPORT_ID"].ToString());//数据库中存储的合同基本数据
            if (moc != null)
            {
                moc.Charge = moc.Total_Price * discount / 100;
                UserContext uc = Session["USER_CONTEXT"] as UserContext;
                if (uc == null)
                {
                    Utility.SiteError("会话过期", Response);
                    return;
                }
                else
                {
                    //更新合同总价
                    dac.UpdateCharge(uc.UserID, moc.Total_Price,moc.Charge, ViewState["REPORT_ID"].ToString());
                    TextBoxCharge.Text =String.Format("{0,9:F2}", moc.Charge);
                    labelInfo.Text = String.Format("更新折扣（合同总价）成功!");
                }
            }

        }
        else
        {
            labelInfo.Text = "折扣率无法识别！";
        }
    }
}
